package com.admin.education.common.jwt;

import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessage;
import com.admin.education.common.response.Result;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor  extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod)
        {
            JwtAuthorize methodJwtAuthorize = ((HandlerMethod) handler).getMethodAnnotation(JwtAuthorize.class);
            Object classJwtAuthorize = ((HandlerMethod) handler).getBean().getClass().getAnnotation(JwtAuthorize.class);
            if (null == methodJwtAuthorize && null == classJwtAuthorize)
            {
                return true;
            }

            if ("OPTIONS".equals(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
                return true;
            } else {
                final String authHeader = request.getHeader("authorization");
                IResponseMessage responseMessage = null;
                String accept =  request.getHeader("Accept");
                if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    if("application/json".equals(accept)) {
                        responseMessage =new ResponseMessage(Result.Error,"请输入正确的请求头");
                        response.getWriter().print(JSON.toJSON(responseMessage));
                    }
                    return  false;
                }

                final String token = authHeader.substring(7);

                try {
                    final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
                    request.setAttribute("claims", claims);
                } catch (final SignatureException e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    if("application/json".equals(accept)) {
                        responseMessage =new ResponseMessage(Result.Error,"请输入正确的Token");
                        response.getWriter().print(JSON.toJSON(responseMessage));
                    }
                    return  false;
                }

                return true;

            }
        }
        return  true;
    }
}
